/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.kaijie.admin.modules.sys.controller;

import com.kaijie.admin.common.annotation.SysLog;
import com.kaijie.admin.common.utils.Constant;
import com.kaijie.admin.common.utils.R;
import com.kaijie.admin.modules.sys.entity.SysMenuEntity;
import com.kaijie.admin.modules.sys.service.SysMenuService;
import com.kaijie.exception.RRException;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 系统菜单
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends AbstractController {
    @Autowired
    private SysMenuService sysMenuService;

    private List<Map<String, Object>> convertMenu(List<?> menuList) {
        List<Map<String, Object>> menuMapList = new LinkedList<>();
        for (Object obj : menuList) {
            SysMenuEntity menu = (SysMenuEntity) obj;
            Map<String, Object> menuMap = new HashMap<>();
            menuMap.put("title", menu.getName());
            menuMap.put("icon", menu.getIcon());
            menuMap.put("href", menu.getUrl());
            menuMap.put("target", "_self");
            if (menu.getList() != null) {
                List<Map<String, Object>> childList = convertMenu(menu.getList());
                menuMap.put("child", childList);
            }
            menuMapList.add(menuMap);
        }
        return menuMapList;
    }

    @RequestMapping("/init")
    public R init() {
        List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(getUserId());
        List<Map<String, Object>> menuMapList = convertMenu(menuList);
        Map<String, Object> menuInfo = new HashMap<>();
        menuInfo.put("title", "后台管理系统");
        menuInfo.put("icon", "");
        menuInfo.put("href", "");
        menuInfo.put("target", "_self");
        menuInfo.put("child", menuMapList);
        List<Map<String, Object>> menuInfoList = new LinkedList<>();
        menuInfoList.add(menuInfo);

        Map<String, Object> result = new HashMap<>();
        result.put("menuInfo", menuInfoList);

        Map<String, String> homeMap = new HashMap<>();
        homeMap.put("title", "首页");
        homeMap.put("href", "main.html");
        Map<String, Object> logoMap = new HashMap<>();
        logoMap.put("title", "职校后台");
        logoMap.put("image", "statics/images/logo.png");
        logoMap.put("href", "");

        result.put("homeInfo", homeMap);
        result.put("logoInfo", logoMap);

        return R.ok(result);
    }

    /**
     * 导航菜单
     */
    @RequestMapping("/nav")
    public R nav() {
        List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(getUserId());
        return R.ok().put("menuList", menuList);
    }

    /**
     * 所有菜单列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:menu:list")
    public R list(){
        List<SysMenuEntity> menuList = sysMenuService.list();
        for (SysMenuEntity menu : menuList) {
            if (menu==null||menu.getType() == 0) {
                menu.setOpen(true);
            }
        }

        return R.ok()
                .put("count", menuList.size())
                .put("data", menuList);
    }

    /**
     * 菜单树列表
     */
    @RequestMapping("/tree")
    @RequiresPermissions("sys:menu:tree")
    public List<Map<String, Object>> tree(@RequestParam(value = "type", defaultValue = "0") Integer type) {
        List<SysMenuEntity> menuList = sysMenuService.query().le(type>0, "type", type).list();
        List<Map<String, Object>> menuListTree = menuChildTree(0L, menuList);

        return menuListTree;
    }

    private List<Map<String, Object>> menuChildTree(Long parentId, List<SysMenuEntity> menuList) {
		List<Map<String, Object>> menuListTree = new LinkedList<>();
		for (SysMenuEntity menuEntity : menuList) {
			if (parentId.equals(menuEntity.getParentId())) {
				Map<String, Object> nodeMap = new HashMap<>();
				nodeMap.put("id", menuEntity.getMenuId());
				nodeMap.put("title", menuEntity.getName());
				nodeMap.put("parentId", menuEntity.getParentId());
				nodeMap.put("checkArr", "0");
				List<Map<String, Object>> childListTree = menuChildTree(menuEntity.getMenuId(), menuList);
				nodeMap.put("children", childListTree);
				menuListTree.add(nodeMap);
			}
		}
		return menuListTree;
	}

    /**
     * 选择菜单(添加、修改菜单)
     */
    @RequestMapping("/select")
    @RequiresPermissions("sys:menu:select")
    public R select() {
        //查询列表数据
        List<SysMenuEntity> menuList = sysMenuService.queryNotButtonList();

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("一级菜单");
        root.setParentId(-1L);
        root.setOpen(true);
        menuList.add(root);

        return R.ok().put("menuList", menuList);
    }

    /**
     * 菜单信息
     */
    @RequestMapping("/info/{menuId}")
    @RequiresPermissions("sys:menu:info")
    public R info(@PathVariable("menuId") Long menuId) {
        SysMenuEntity menu = sysMenuService.getById(menuId);
        return R.ok().put("menu", menu);
    }

    /**
     * 保存
     */
    @SysLog("保存菜单")
    @RequestMapping("/save")
    @RequiresPermissions("sys:menu:save")
    public R save(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);

        sysMenuService.save(menu);

        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改菜单")
    @RequestMapping("/update")
    @RequiresPermissions("sys:menu:update")
    public R update(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);

        sysMenuService.updateById(menu);

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog("删除菜单")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:menu:delete")
    @Transactional
    public R delete(@RequestBody Long[] menuIds) {
        for (Long menuId : menuIds) {
            if (menuId <= 31) {
                throw new RRException("系统菜单，不能删除");
            }

            //判断是否有子菜单或按钮
            List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
            if (menuList.size() > 0) {
                throw new RRException("请先删除子菜单或按钮");
            }

            sysMenuService.delete(menuId);
        }

        return R.ok();
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenuEntity menu) {
        if (StringUtils.isBlank(menu.getName())) {
            throw new RRException("菜单名称不能为空");
        }

        if (menu.getParentId() == null) {
            throw new RRException("上级菜单不能为空");
        }

        //菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                throw new RRException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if (menu.getParentId() != 0) {
            SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if (menu.getType() == Constant.MenuType.CATALOG.getValue() ||
                menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new RRException("上级菜单只能为目录类型");
            }
            return;
        }

        //按钮
        if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new RRException("上级菜单只能为菜单类型");
            }
            return;
        }
    }
}
